# This is a sample Python script.
import random
from pypbc import *
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

def primes1(start, end):
	# 用条件表达式判断是否大于2
    start = 2 if start < 2 else start
    # 循环嵌套的方式生成素数生成器对象，自身嵌套，自己除以自己，判断余数
    for i in range(start, end+1):
        for j in range(2, i):
            if i % j == 0:
                break
        else:
            yield i

primes = []
for i in primes1(1,100):
    primes.append(i)

def setup():
    Attrs = [1,2,3,4,5]
    alen = len(Attrs)
    t = set()
    while len(t)<=alen:
        temp = random.choice(primes)
        t.add(temp)

    return t

def genPBC(qbits=512,rbits=160):
    params = Parameters(qbits=qbits,rbits=rbits)
    pairing = Pairing(params)
    return pairing

def Enc(M,gama,PK,Y):
    #将M映射到G2
    M = Element.from_hash(pairing, GT, M)  # dont need manual hash,automic get data hash
    s = random.choice(primes)
    E_b = M*(Y**s)
    E_s = []
    for gi in gama:
        Ti=PK[gi]
        E_s.append([Ti**s,gi])
    return [gama,E_b,E_s]

def Dec(E,D,ACT):

    def findindex(D,attr):
        for index in range(len(D)):
            if(D[index][1] == attr):
                return index
        return 0
    def findLeaf(node):
        if(node.type == 'attr'):
            index1 = findindex(D,node.value)
            if(index1):
                index2 = findindex(E[2],node.value)
                return  pairing.apply(D[index1][0],E[2][index2]) #if i in gama retuen e(dx,ei)
            else:
                return  1#G2 dedibianjie (zuixiaozhi cankao gelun
        for child in node.child:
            Fz = findLeaf(child)

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    MK = setup()
    MK = list(MK)
    print('MK:' ,MK)
    print('y:',MK[0])
    print('t:',MK[1:])
    y=MK[0]
    t=MK[1:]

    pairing = genPBC()
    g = Element.random(pairing,G2)



    PK = []

    Y = pairing.apply(g,g)**y


    for ti in t:
        T = g**ti
        PK.append(T)

    print('PK:',PK)
    print('Y:',Y)
    #print(help(Element))
    E = Enc('123',[2,4],PK,Y)
    print('Enc Data:',E)